import { defineStore } from 'pinia'
import { getInfo } from '@/api/user'
import { ElMessage } from 'element-plus'
/*defineStore 是需要传参数的，其中第一个参数是id，就是一个唯一的值，
简单点说就可以理解成是一个命名空间.
第二个参数就是一个对象，里面有三个模块需要处理，第一个是 state，
第二个是 getters，第三个是 actions。
*/
export const userStore = defineStore("user", {
    state:()=>{
        return {
            token: '',
            username: '',
            password: '',
            name: '',
            userId: '',
            avatar: '',
            dName: '',
            cName: '',
            jName: '',
            bName: '',
            cmCanBegin: '',
            cmCanMonitor: '',
            cmCanEngineer: '',
            cmCanConfirm: ''
        }
    },
    getters: {
        getToken(): string {
            return this.token
        },
        getAvatar(): string {
            return this.avatar
        },
        getUserName(): string {
            return this.username
        },
        getUserID(): string {
            return this.userId
        },
        getCmCanBegin(): string {
            return this.cmCanBegin
        },
        getCmCanMonitor(): string {
            return this.cmCanMonitor
        },
        getCmCanEngineer(): string {
            return this.cmCanEngineer
        },
        getCmCanConfirm(): string {
            return this.cmCanConfirm
        },
    },

    actions: {
        userInfo(token:any){
            this.token = token
            localStorage.setItem('admin-token', this.token)
            getInfo().then(res => {
               if (res.code === 200) {
                   this.cmCanBegin = res.data.cmCanBegin
                   this.cmCanConfirm = res.data.cmCanConfirm
                   this.cmCanEngineer = res.data.cmCanEngineer
                   this.cmCanMonitor = res.data.cmCanMonitor
                   this.avatar = res.data.avatar
                   localStorage.setItem('avatar', this.avatar)
               } else {
                   localStorage.removeItem('admin-token')
                   ElMessage.error('登录失效！重新登陆！')
               }
            })
        },
        persist: true

    }
})

//暴露这个useCounter模块
export default userStore